﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using LKVMLMLib;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Data;
using System.Web;
using System.ServiceModel.Channels;
using System.Security.Cryptography;
using System.Data.Entity.SqlServer;

namespace LKVService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "User" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select User.svc or User.svc.cs at the Solution Explorer and start debugging.
    public class User
    {
        public void ResetData()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var objCtx = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext;
                objCtx.ExecuteStoreCommand("TRUNCATE TABLE [Profit]");
                db.Orders.ToList().ForEach(x => { db.Orders.Remove(x); });
                objCtx.ExecuteStoreCommand("TRUNCATE TABLE [Payment_User]");
                objCtx.ExecuteStoreCommand("TRUNCATE TABLE [CommissionMonthYear]");
                db.UserProfiles.Where(w => w.UserName != "root").ToList().ForEach(x => { db.UserProfiles.Remove(x); });
                //Tuong them:reset Left-Right cho root
                var _root = db.UserProfiles.Where(x => x.UserName == "root").SingleOrDefault();
                if (_root != null)
                {
                    _root.Left = null;
                    _root.Right = null;
                }
                db.SaveChanges();
                object[] parameters = { };
                var plugins = db.CommissionConfigs.Where(t => (t.Status == true));
                foreach (var plugin in plugins.ToList())
                {

                    string plugin_name = plugin.CommissionName + ".ExecuteCommission";
                    try
                    {
                        var instance = System.Activator.CreateInstance(Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service"));
                        var class_name = Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service");
                        var method = class_name.GetMethod("resetData");
                        method.Invoke(instance, parameters);

                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
            }

        }
        public string GetData(int value)
        {
            return string.Format("-- : {0}", value);
        }
        public int getPackageIdOfUser(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                int _order = db.Orders.Where(x => x.UserId == userId).FirstOrDefault() != null ? Convert.ToInt32(db.Orders.Where(x => x.UserId == userId).FirstOrDefault().Package_id) : 0;
                return _order;
            }
        }
        public double getOrderValOfUser(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                double _order = db.Orders.Where(x => x.UserId == userId).FirstOrDefault() != null ? Convert.ToDouble(db.Orders.Where(x => x.UserId == userId).FirstOrDefault().Amount) : 0;
                return _order;
            }
        }
        public bool? getUserConfig()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.UserConfigs.FirstOrDefault().AGUsername;
            }
        }
        public UserProfile getUser(string username, string pass)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var user = db.UserProfiles.Where(w => w.UserName == username && w.Password == pass).SingleOrDefault();
                return user;
            }
        }
        public UserProfile getUserByGroup(int GroupID)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var user = db.UserProfiles.Where(w => w.GruopID == GroupID).SingleOrDefault();
                if (user != null) return user;
                return null;
            }
        }
        public UserProfile[] finUserContainName(string userName)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(x => x.UserName.Contains(userName + "-")).ToArray();
            }
        }
        public UserProfile[] finSubUserContainName(string userName)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(x => x.UserName.Contains(userName + "@")).ToArray();
            }
        }
        public UserProfile[] getListUser()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var rt = db.UserProfiles.ToArray();
                return rt;
            }
        }
        public UserProfile findUserById(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var user = db.UserProfiles.Where(x => x.UserId == userId).FirstOrDefault();
                return user;
            }
        }
        public UserProfile findUserByUserName(string _userName)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                if (String.IsNullOrWhiteSpace(_userName) && _userName != string.Empty)
                {
                    var user = db.UserProfiles.Where(x => x.Parent_ID == 0).AsEnumerable().Select(
                        x => new UserProfile
                        {
                            CreateDate = x.CreateDate,
                            DIACHI = x.DIACHI,
                            EMAIL = x.EMAIL,
                            GIOITINH = x.GIOITINH,
                            GruopID = x.GruopID,
                            HoanVon = x.HoanVon,
                            HOTEN = x.HOTEN,
                            HOTENVOHOACCHONG = x.HOTENVOHOACCHONG,
                            Level = x.Level,
                            LevelUpdate = x.LevelUpdate,
                            MSTCANHAN = x.MSTCANHAN,
                            NganHang = x.NganHang,
                            NGAYCAP = x.NGAYCAP,
                            NGAYSINH = x.NGAYSINH,
                            NOICAP = x.NOICAP,
                            NOISINH = x.NOISINH,
                            Package = x.Package,
                            PackageID = x.PackageID,
                            Parent_ID = x.Parent_ID,
                            PreLevel = x.PreLevel,
                            QUOCGIA = x.QUOCGIA,
                            SCMNDCUAVOHOACCHONG = x.SCMNDCUAVOHOACCHONG,
                            SDTNHARIENG = x.SDTNHARIENG,
                            SDTNOILAMVIEC = x.SDTNOILAMVIEC,
                            SOCMND = x.SOCMND,
                            SoTaiKhoan = x.SoTaiKhoan,
                            Status = x.Status,
                            THANHPHO = x.THANHPHO,
                            UserId = x.UserId,
                            Left = x.Left,
                            Right = x.Right,
                            UserName = x.UserName,
                            ParentB_ID = x.ParentB_ID,
                            Password = x.Password != null ? "" : ""
                        }
                        ).FirstOrDefault();
                    return user;
                }
                else
                {
                    var user = db.UserProfiles.Where(x => x.UserName.Equals(_userName.Trim())).ToList()
                        .Select(
                            x => new UserProfile
                            {
                                CreateDate = x.CreateDate,
                                DIACHI = x.DIACHI,
                                EMAIL = x.EMAIL,
                                GIOITINH = x.GIOITINH,
                                GruopID = x.GruopID,
                                HoanVon = x.HoanVon,
                                HOTEN = x.HOTEN,
                                HOTENVOHOACCHONG = x.HOTENVOHOACCHONG,
                                Level = x.Level,
                                LevelUpdate = x.LevelUpdate,
                                MSTCANHAN = x.MSTCANHAN,
                                NganHang = x.NganHang,
                                NGAYCAP = x.NGAYCAP,
                                NGAYSINH = x.NGAYSINH,
                                NOICAP = x.NOICAP,
                                NOISINH = x.NOISINH,
                                Package = x.Package,
                                PackageID = x.PackageID,
                                Parent_ID = x.Parent_ID,
                                //Payment_User = x.Payment_User, 
                                PreLevel = x.PreLevel,
                                QUOCGIA = x.QUOCGIA,
                                SCMNDCUAVOHOACCHONG = x.SCMNDCUAVOHOACCHONG,
                                SDTNHARIENG = x.SDTNHARIENG,
                                SDTNOILAMVIEC = x.SDTNOILAMVIEC,
                                SOCMND = x.SOCMND,
                                SoTaiKhoan = x.SoTaiKhoan,
                                Status = x.Status,
                                THANHPHO = x.THANHPHO,
                                UserId = x.UserId,
                                Left = x.Left,
                                Right = x.Right,
                                UserName = x.UserName,
                                ParentB_ID = x.ParentB_ID,
                                Password = x.Password != null ? "" : ""
                            }
                        ).FirstOrDefault();
                    return user;
                }
            }
        }
        public UserProfile[] getListByParent(int _parentId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var rt = db.UserProfiles.Where(x => x.Parent_ID == _parentId).ToList().Select(
                                x => new UserProfile
                                {
                                    CreateDate = x.CreateDate,
                                    DIACHI = x.DIACHI,
                                    EMAIL = x.EMAIL,
                                    GIOITINH = x.GIOITINH,
                                    GruopID = x.GruopID,
                                    HoanVon = x.HoanVon,
                                    HOTEN = x.HOTEN,
                                    HOTENVOHOACCHONG = x.HOTENVOHOACCHONG,
                                    Level = x.Level,
                                    Left = x.Left,
                                    Right = x.Right,
                                    LevelUpdate = x.LevelUpdate,
                                    MSTCANHAN = x.MSTCANHAN,
                                    NganHang = x.NganHang,
                                    NGAYCAP = x.NGAYCAP,
                                    NGAYSINH = x.NGAYSINH,
                                    NOICAP = x.NOICAP,
                                    NOISINH = x.NOISINH,
                                    Package = x.Package,
                                    PackageID = x.PackageID,
                                    Parent_ID = x.Parent_ID,
                                    ParentB_ID = x.ParentB_ID,
                                    //Payment_User = x.Payment_User,
                                    PreLevel = x.PreLevel,
                                    QUOCGIA = x.QUOCGIA,
                                    SCMNDCUAVOHOACCHONG = x.SCMNDCUAVOHOACCHONG,
                                    SDTNHARIENG = x.SDTNHARIENG,
                                    SDTNOILAMVIEC = x.SDTNOILAMVIEC,
                                    SOCMND = x.SOCMND,
                                    SoTaiKhoan = x.SoTaiKhoan,
                                    Status = x.Status,
                                    THANHPHO = x.THANHPHO,
                                    UserId = x.UserId,
                                    UserName = x.UserName
                                }
                            );
                return rt.ToArray();
            }
        }
        public int totalUserF1(int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(w => w.Parent_ID == UserId).Count();
            }
        }
        public int totalUserF2(int UserId)
        {
            int totalUser = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var ListF1 = db.UserProfiles.Where(w => w.Parent_ID == UserId).ToList();
                foreach (UserProfile item in ListF1)
                {
                    totalUser += this.totalUserByParentId(item.UserId);
                }
                return totalUser;
            }
        }
        public dynamic totalUserF3(int UserId)
        {

            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var transactionDB = new Transaction();
                var ListUserF1 = db.UserProfiles.Where(w => w.Parent_ID == UserId).ToList();
                dynamic TotalUser = new System.Dynamic.ExpandoObject();
                TotalUser.F1 = 0;
                TotalUser.F2 = 0;
                TotalUser.F3 = 0;
                TotalUser.TotalCommissionF1 = 0;
                TotalUser.TotalCommissionF2 = 0;
                TotalUser.TotalCommissionF3 = 0;
                if (ListUserF1 != null)
                {
                    TotalUser.F1 = ListUserF1.Count();
                    foreach (UserProfile item in ListUserF1)
                    {
                        TotalUser.TotalCommissionF1 += transactionDB.getTotalCommission(item.UserId).Value;
                        var ListUserF2 = db.UserProfiles.Where(w => w.Parent_ID == item.UserId).ToList();
                        TotalUser.F2 += ListUserF2.Count();
                        foreach (UserProfile itemf2 in ListUserF2)
                        {
                            TotalUser.TotalCommissionF2 += transactionDB.getTotalCommission(itemf2.UserId).Value;
                            var ListUserF3 = db.UserProfiles.Where(w => w.Parent_ID == itemf2.UserId).ToList();
                            TotalUser.F3 += ListUserF3.Count();
                            foreach (UserProfile itemf3 in ListUserF3)
                            {
                                TotalUser.TotalCommissionF3 += transactionDB.getTotalCommission(itemf3.UserId).Value;
                            }
                        }
                    }
                }
                return TotalUser;
            }
        }
        public int totalUserByParentId(int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(w => w.Parent_ID == UserId).Count();
            }
        }
        public UserProfile[] getListByBinaryId(int _binaryId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var rt = db.UserProfiles.Where(x => x.ParentB_ID == _binaryId).ToList().Select(
                            x => new UserProfile
                            {
                                ParentB_ID = x.ParentB_ID,
                                CreateDate = x.CreateDate,
                                DIACHI = x.DIACHI,
                                EMAIL = x.EMAIL,
                                Left = x.Left,
                                Right = x.Right,
                                GIOITINH = x.GIOITINH,
                                GruopID = x.GruopID,
                                HoanVon = x.HoanVon,
                                HOTEN = x.HOTEN,
                                HOTENVOHOACCHONG = x.HOTENVOHOACCHONG,
                                Level = x.Level,
                                LevelUpdate = x.LevelUpdate,
                                MSTCANHAN = x.MSTCANHAN,
                                NganHang = x.NganHang,
                                NGAYCAP = x.NGAYCAP,
                                NGAYSINH = x.NGAYSINH,
                                NOICAP = x.NOICAP,
                                NOISINH = x.NOISINH,
                                Package = x.Package,
                                PackageID = x.PackageID,
                                Parent_ID = x.Parent_ID,
                                //Payment_User = x.Payment_User,
                                PreLevel = x.PreLevel,
                                QUOCGIA = x.QUOCGIA,
                                SCMNDCUAVOHOACCHONG = x.SCMNDCUAVOHOACCHONG,
                                SDTNHARIENG = x.SDTNHARIENG,
                                SDTNOILAMVIEC = x.SDTNOILAMVIEC,
                                SOCMND = x.SOCMND,
                                SoTaiKhoan = x.SoTaiKhoan,
                                Status = x.Status,
                                THANHPHO = x.THANHPHO,
                                UserId = x.UserId,
                                UserName = x.UserName
                            }
                        );
                return rt.ToArray();
            }
        }
        public Group findGroupById(int groupId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Groups.Where(x => x.GroupID == groupId).SingleOrDefault();
            }
        }
        public Group findGroupByGroupName(string GroupName)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Groups.Where(x => x.GroupName == GroupName).FirstOrDefault();
            }
        }
        public int AddUserWithPackge(UserProfile c, string position = "Left", int exist_account = 0, int package = 1)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var staticdb = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var c_uid = this.AddUser(c, position, exist_account);
                if (c_uid > 0 && package > 1)
                {
                    object[] parameters = { c_uid, package, DateTime.Now };

                    var plugins = staticdb.CommissionConfigs.Where(t => (t.Status == true));
                    foreach (var plugin in plugins.ToList())
                    {
                        string plugin_name = plugin.CommissionName + ".PackageAction";
                        try
                        {
                            var instance = System.Activator.CreateInstance(Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service"));
                            var class_name = Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service");
                            var method = class_name.GetMethod("AfterPackageActived");
                            method.Invoke(instance, parameters);
                        }
                        catch (Exception ex)
                        {
                            continue;
                        }
                    }
                }
                return c_uid;
            }
        }
        public int AddUser(UserProfile c, string position = "Left", int exist_account = 0)
        {
            int _return = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var userconfig = db.UserConfigs.FirstOrDefault();
                var configParent = this.getConfigTree();
                int? Parent_ID = 0, ParentB_ID = 0;
                if (configParent.Option_1 != true)
                {
                    Parent_ID = c.Parent_ID;
                    c.Parent_ID = null;
                }
                if (configParent.Option_2 != true)
                {
                    ParentB_ID = c.ParentB_ID;
                    c.ParentB_ID = null;
                }

                //check account da ton tai chua
                var _sameUserName = db.UserProfiles.Where(x => x.UserName.Equals(c.UserName)).FirstOrDefault();
                if (_sameUserName != null)
                    return 0;
                //kiem tra co them Binary khong, co thi Add -->UserBinary
                int _nextId = Convert.ToInt32(db.Database.SqlQuery<decimal>("SELECT IDENT_CURRENT ('UserProfile')", new object[0]).FirstOrDefault()) + 1;

                if (c.ParentB_ID != null && c.ParentB_ID != 0)
                {
                    //add user binary
                    var _exitsUser = db.UserProfiles.Where(x => x.UserId == c.ParentB_ID).SingleOrDefault();
                    if (_exitsUser == null)
                        return 0;
                    if (position == "Left")
                    {
                        var _checkUserLeft = db.UserProfiles.Where(x => x.UserId == _exitsUser.Left).SingleOrDefault();
                        if (_checkUserLeft != null)
                            return 0;
                        else
                            _exitsUser.Left = _nextId;

                    }
                    else
                    {
                        var _checkUserRight = db.UserProfiles.Where(x => x.UserId == _exitsUser.Right).SingleOrDefault();
                        if (_checkUserRight != null)
                            return 0;
                        else
                            _exitsUser.Right = _nextId;
                    }
                }
                try
                {
                    c.Level = 1;
                    c.CreateDate = DateTime.Now;
                    c.IsFirst = true; //để kiểm tra xem có phải lần đầu kích pin ko
                    db.UserProfiles.Add(c);
                    db.SaveChanges();
                    List<Wallet> Wallets = db.Wallets.Where(w => w.Withdraw != null && w.Withdraw != false).ToList();
                    foreach (var item in Wallets)
                    {
                        var WalletItem = new Wallet_Detail();
                        WalletItem.UserID = c.UserId;
                        WalletItem.WalletID = item.Id;
                        WalletItem.Balance = 0;
                        db.Wallet_Detail.Add(WalletItem);
                    }
                    db.SaveChanges();

                }
                catch
                {
                    return 0;
                }
                db.SaveChanges();

                // add plugin              
                var plugins = db.CommissionConfigs.Where(t => (t.Status == true));
                object[] parameters = { c.UserId, Parent_ID, ParentB_ID };
                foreach (var plugin in plugins.ToList())
                {
                    string plugin_name = plugin.CommissionName + ".ExecuteCommission";
                    try
                    {
                        var instance = System.Activator.CreateInstance(Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service"));
                        var class_name = Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service");
                        var method = class_name.GetMethod("onUserAdded");
                        method.Invoke(instance, parameters);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
                // end plugin

                _return = c.UserId;
            }
            return _return;
        }
        /// <summary>
        /// Methol add user not plusgin onUserAdded
        /// </summary>
        /// <param name="c"></param>
        /// <param name="position"></param>
        /// <param name="exist_account"></param>
        /// <returns></returns>
        public int AddUserNotPlugin(UserProfile c, string position = "Left", int exist_account = 0)
        {
            int _return = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var userconfig = db.UserConfigs.FirstOrDefault();
                var configParent = this.getConfigTree();
                int? Parent_ID = 0, ParentB_ID = 0;
                if (configParent.Option_1 != true)
                {
                    Parent_ID = c.Parent_ID;
                    c.Parent_ID = null;
                }
                if (configParent.Option_2 != true)
                {
                    ParentB_ID = c.ParentB_ID;
                    c.ParentB_ID = null;
                }

                //check account da ton tai chua
                var _sameUserName = db.UserProfiles.Where(x => x.UserName.Equals(c.UserName)).FirstOrDefault();
                if (_sameUserName != null)
                    return 0;
                if (exist_account != 0)
                {
                    var exist_account_db = db.UserProfiles.Where(w => w.UserId == exist_account).SingleOrDefault();
                    if (exist_account_db == null) return 0;
                    var latestusername = db.UserProfiles.Where(w => w.UserName.Contains(exist_account_db.UserName)).OrderByDescending(o => o.UserId).Select(s => s.UserName).FirstOrDefault();
                    var tmp = latestusername.Split('-');
                    if (tmp.Count() == 2)
                        c.UserName = exist_account_db.UserName + "-" + (Convert.ToInt32(tmp[1]) + 1).ToString("000");
                    else c.UserName = exist_account_db.UserName + "-001";
                }
                else
                {
                    if (c.UserName == null)
                    {
                        if (userconfig.AGUsername == true)
                        {
                            var oldID = db.UserProfiles.OrderByDescending(o => o.UserId).Select(s => s.UserId).FirstOrDefault();
                            if (oldID == null) c.UserName = userconfig.Suffix + "000001";
                            else c.UserName = userconfig.Suffix + (oldID + 1).ToString("000000");
                        }
                        else
                            return 0;

                    }
                }
                //kiem tra co them Binary khong, co thi Add -->UserBinary
                int _nextId = Convert.ToInt32(db.Database.SqlQuery<decimal>("SELECT IDENT_CURRENT ('UserProfile')", new object[0]).FirstOrDefault()) + 1;

                if (c.ParentB_ID != null && c.ParentB_ID != 0)
                {
                    //add user binary
                    var _exitsUser = db.UserProfiles.Where(x => x.UserId == c.ParentB_ID).SingleOrDefault();
                    if (_exitsUser == null)
                        return 0;
                    if (position == "Left")
                    {
                        var _checkUserLeft = db.UserProfiles.Where(x => x.UserId == _exitsUser.Left).SingleOrDefault();
                        if (_checkUserLeft != null)
                            return 0;
                        else
                            _exitsUser.Left = _nextId;

                    }
                    else
                    {
                        var _checkUserRight = db.UserProfiles.Where(x => x.UserId == _exitsUser.Right).SingleOrDefault();
                        if (_checkUserRight != null)
                            return 0;
                        else
                            _exitsUser.Right = _nextId;
                    }
                }
                try
                {
                    c.Level = 1;
                    c.CreateDate = DateTime.Now;
                    db.UserProfiles.Add(c);
                    db.SaveChanges();
                    List<Wallet> Wallets = db.Wallets.ToList();
                    foreach (var item in Wallets)
                    {
                        var WalletItem = new Wallet_Detail();
                        WalletItem.UserID = c.UserId;
                        WalletItem.WalletID = item.Id;
                        WalletItem.Balance = 0;
                        db.Wallet_Detail.Add(WalletItem);
                    }
                    db.Share_User.Add(new Share_User { UserId = c.UserId, Balance = 0 });
                    db.SaveChanges();

                }
                catch
                {
                    return 0;
                }
                db.SaveChanges();

                // add plugin              
                var plugins = db.CommissionConfigs.Where(t => (t.Status == true));
                object[] parameters = { c.UserId, Parent_ID, ParentB_ID };
                foreach (var plugin in plugins.ToList())
                {
                    string plugin_name = plugin.CommissionName + ".ExecuteCommission";
                    try
                    {
                        var instance = System.Activator.CreateInstance(Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service"));
                        var class_name = Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service");
                        //var method = class_name.GetMethod("onUserAdded");
                        //method.Invoke(instance, parameters);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
                // end plugin

                _return = c.UserId;
            }
            return _return;
        }
        public int UpdateUser(UserProfile OUserEdit, string position = "Left")
        {
            // 0: user edit khong ton tai 
            // 1: thay đổi parentId/BinaryId không thể từ cha xuống con
            // 2: Binary cha đã đủ 2 con
            // 3: Không thể di chuyển root
            // 4: Left/Right không trống
            // 5: thành công
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var UserEdit = db.UserProfiles.Where(w => w.UserId == OUserEdit.UserId).SingleOrDefault();
                if (UserEdit == null) return 0;
                //if (UserEdit.Parent_ID == 0 || UserEdit.UserName == "root")
                //    return 3;
                //neu cap nhat Parent ID
                if (UserEdit.Parent_ID != OUserEdit.Parent_ID)
                {
                    var userToEdit = db.UserProfiles.Where(s => s.UserId == OUserEdit.Parent_ID).FirstOrDefault();
                    if (userToEdit == null)
                        return 0;
                    var check = userToEdit;
                    while (check != null)
                    {
                        if (check.UserId == UserEdit.UserId)
                            return 1;
                        check = db.UserProfiles.Where(w => w.UserId == check.Parent_ID).SingleOrDefault();
                    }
                    UserEdit.Parent_ID = OUserEdit.Parent_ID;
                }
                //neu cap nhat Binary ID
                if (UserEdit.ParentB_ID != OUserEdit.ParentB_ID)
                {
                    var userBinaryToEdit = db.UserProfiles.Where(s => s.UserId == OUserEdit.ParentB_ID).FirstOrDefault();
                    if (userBinaryToEdit == null)
                        return 0;
                    var listChildBinaryToEdit = db.UserProfiles.Where(s => s.ParentB_ID == userBinaryToEdit.UserId).ToList();
                    if (listChildBinaryToEdit.Count() == 2)
                        return 2;
                    if (position == "Left")
                    {
                        if (userBinaryToEdit.Left != null)
                            return 4;
                        else
                            userBinaryToEdit.Left = OUserEdit.UserId;
                    }
                    if (position == "Right")
                    {
                        if (userBinaryToEdit.Right != null)
                            return 4;
                        else
                            userBinaryToEdit.Right = OUserEdit.UserId;
                    }
                    var check = userBinaryToEdit;
                    while (check != null)
                    {
                        if (check.UserId == UserEdit.UserId)
                            return 1;
                        check = db.UserProfiles.Where(w => w.UserId == check.ParentB_ID).SingleOrDefault();
                    }
                    var old_pB = db.UserProfiles.Where(w => w.UserId == UserEdit.ParentB_ID).SingleOrDefault();
                    if (old_pB.Left == UserEdit.UserId)
                        old_pB.Left = null;
                    else if (old_pB.Right == UserEdit.UserId)
                        old_pB.Right = null;
                    UserEdit.ParentB_ID = OUserEdit.ParentB_ID;
                }
                this.mapUserProfile(UserEdit, OUserEdit);
                db.SaveChanges();
                return 5;
            }
        }
        // change pass word for user
        public int changPassword(UserProfile user)
        {
            int _return = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var d = db.UserProfiles.Where(w => w.UserId == user.UserId && w.UserId == user.UserId).FirstOrDefault();
                d.Password = user.Password;
                d.p = user.p;
                db.SaveChanges();
                _return = 1;
            }
            return _return;
        }
        public bool changeBanks(int UserId, string Payer)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var PerfectMoneyAcc = db.PerfectMoneyUsers.Where(w => w.UserId == UserId).FirstOrDefault();
                if (PerfectMoneyAcc == null)
                {
                    var AccountPerfectMoney = new PerfectMoneyUser();
                    AccountPerfectMoney.UserId = UserId;
                    AccountPerfectMoney.Payer = Payer;
                    db.PerfectMoneyUsers.Add(AccountPerfectMoney);
                }
                else
                {
                    PerfectMoneyAcc.Payer = Payer;
                }
                db.SaveChanges();
            }
            return true;
        }
        public bool changeBankQueProject(int UserId, string Payer)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var userProFile = db.UserProfiles.Where(w => w.UserId == UserId).FirstOrDefault();
                if (userProFile != null)
                {
                    userProFile.SoTaiKhoan = Payer;
                    db.SaveChanges();
                    return true;
                }
                else return false;
            }
        }
        private void mapUserProfile(UserProfile UserEdit, UserProfile OUserEdit)
        {
            UserEdit.UserName = OUserEdit.UserName;
            UserEdit.GruopID = OUserEdit.GruopID;
            UserEdit.CreateDate = OUserEdit.CreateDate;
            UserEdit.QUOCGIA = OUserEdit.QUOCGIA;
            UserEdit.DIACHI = OUserEdit.DIACHI;
            UserEdit.EMAIL = OUserEdit.EMAIL;
            UserEdit.GIOITINH = OUserEdit.GIOITINH;
            UserEdit.HOTENVOHOACCHONG = OUserEdit.HOTENVOHOACCHONG;
            UserEdit.MSTCANHAN = OUserEdit.MSTCANHAN;
            UserEdit.NGAYCAP = OUserEdit.NGAYCAP;
            UserEdit.NGAYSINH = OUserEdit.NGAYCAP;
            UserEdit.THANHPHO = OUserEdit.THANHPHO;
            UserEdit.SOCMND = OUserEdit.SOCMND;
            UserEdit.SCMNDCUAVOHOACCHONG = OUserEdit.SCMNDCUAVOHOACCHONG;
            UserEdit.NOICAP = OUserEdit.NOICAP;
            UserEdit.NOISINH = OUserEdit.NOISINH;
            UserEdit.HOTEN = OUserEdit.HOTEN;
            UserEdit.SDTNHARIENG = OUserEdit.SDTNHARIENG;
            UserEdit.SDTNOILAMVIEC = OUserEdit.SDTNOILAMVIEC;
            UserEdit.SoTaiKhoan = OUserEdit.SoTaiKhoan;
            UserEdit.NganHang = OUserEdit.NganHang;
            UserEdit.BankID = OUserEdit.BankID;
        }
        public Tuple<double, double> callSaleUserAndGroupBinary(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var user = db.UserProfiles.Where(x => x.UserId == userId).FirstOrDefault();
                DateTime _dateNow = DateTime.Now.Date;
                DateTime _firstMonth = _dateNow.AddDays((-_dateNow.Day) + 1);
                DateTime _lastMonth = _dateNow.AddMonths(1);
                _lastMonth = _lastMonth.AddDays((-_dateNow.Day) + 1);
                double _saleUser = 0;
                double _saleGroup = 0;
                var _order = db.Orders.Where(w => w.Date >= _firstMonth && w.Date < _lastMonth).ToList();
                if (_order.Count == 0) return new Tuple<double, double>(0, 0);
                _saleUser = Convert.ToDouble(db.Orders.Where(x => x.UserId == user.UserId && x.Date >= _firstMonth && x.Date < _lastMonth).Sum(x => x.Pv));
                var listBinary = new List<UserProfile>();
                populateChildBinary((int)user.UserId, listBinary);
                _saleGroup = Convert.ToDouble(_order.Join(listBinary, p => p.UserId, c => c.UserId, (c, p) => new
                {
                    c.ID,
                    c.Pv,
                    c.Date
                }).Sum(x => x.Pv)); ;

                Tuple<double, double> regain = new Tuple<double, double>(_saleUser, _saleGroup);
                return regain;
            }
        }
        public Tuple<double, double, int, int> calLeftRight(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var user = db.UserProfiles.Where(x => x.UserId == userId).FirstOrDefault();
                double _reLeft = 0;
                double _reRight = 0;
                int _slLeft = 0;
                int _slRight = 0;
                if (user != null)
                {
                    // lấy thành viên trái- phải là F1 của user
                    var _leftOfUser = db.UserProfiles.Where(x => x.UserId == user.Left).FirstOrDefault();
                    var _rightOfUser = db.UserProfiles.Where(x => x.UserId == user.Right).FirstOrDefault();
                    var _order = db.Orders.ToList();
                    //if (_order.Count == 0) return new Tuple<double, double, int, int>(0,0,0,0);
                    if (_leftOfUser != null)
                    {
                        var _listLeft = new List<UserProfile>();
                        populateChildBinary(_leftOfUser.UserId, _listLeft);
                        if (_leftOfUser.Status == true)
                        {
                            _slLeft = _listLeft.Where(w => w.Status == true).Count() + 1;
                        }
                        else
                        {
                            _slLeft = _listLeft.Where(w => w.Status == true).Count();
                        }
                        _reLeft = Convert.ToDouble(_order.Join(_listLeft, p => p.UserId, c => c.UserId, (c, p) => new
                        {

                            c.Amount,

                        }).Sum(x => x.Amount));
                    }
                    if (_rightOfUser != null)
                    {
                        var _listRight = new List<UserProfile>();
                        populateChildBinary(_rightOfUser.UserId, _listRight);
                        if (_rightOfUser.Status == true)
                        {
                            _slRight = _listRight.Where(w => w.Status == true).Count() + 1;
                        }
                        else
                        {
                            _slRight = _listRight.Where(w => w.Status == true).Count();
                        }

                        _reRight = Convert.ToDouble(_order.Join(_listRight, p => p.UserId, c => c.UserId, (c, p) => new
                        {
                            c.Amount,
                        }).Sum(x => x.Amount));
                    }

                }
                Tuple<double, double, int, int> _regain = new Tuple<double, double, int, int>(_reLeft, _reRight, _slLeft, _slRight);

                return _regain;
            }
        }
        public Tuple<double, double> callSaleUSerAndGroupParent(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var user = db.UserProfiles.Where(x => x.UserId == userId).FirstOrDefault(); ;
                DateTime _dateNow = DateTime.Now.Date;
                DateTime _firstMonth = _dateNow.AddDays((-_dateNow.Day) + 1);
                DateTime _lastMonth = _dateNow.AddMonths(1);
                _lastMonth = _lastMonth.AddDays((-_dateNow.Day) + 1);
                double _saleUser = 0;
                double _saleGroup = 0;
                var orderOfMonth = db.Orders.Where(w => w.Date >= _firstMonth && w.Date < _lastMonth).ToList();
                _saleUser = Convert.ToDouble(db.Orders.Where(x => x.UserId == user.UserId && x.Date >= _firstMonth && x.Date < _lastMonth).Sum(x => x.Pv));
                List<UserProfile> childrens = new List<UserProfile>();
                populateChild(user.UserId, childrens);

                _saleGroup = Convert.ToDouble(orderOfMonth.Join(childrens, p => p.UserId, c => c.UserId, (c, p) => new
                {
                    c.ID,
                    c.Pv,
                    c.Date
                }).Sum(x => x.Pv));

                Tuple<double, double> regain = new Tuple<double, double>(_saleUser, _saleGroup);
                return regain;
            }
        }
        public void populateChild(int parentId, List<UserProfile> childrens)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var da = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                da.Configuration.ProxyCreationEnabled = false;
                var lsChild = da.UserProfiles.Where(x => x.Parent_ID == parentId).ToList();
                childrens.AddRange(lsChild);
                foreach (var item in lsChild)
                {
                    populateChild(item.UserId, childrens);
                }
            }
        }
        public void populateChildBinary(int parentB_Id, List<UserProfile> childrensB)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var dd = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                dd.Configuration.ProxyCreationEnabled = false;
                var lsChild = dd.UserProfiles.Where(x => x.ParentB_ID == parentB_Id).ToList();
                childrensB.AddRange(lsChild);
                foreach (var item in lsChild)
                {
                    populateChildBinary(item.UserId, childrensB);
                }
            }
        }
        public int getDownLine(int userId)
        {
            List<UserProfile> _getChild = new List<UserProfile>();
            populateChild(userId, _getChild);
            return _getChild.Count();
        }
        public int getDownLineBinary(int userId)
        {
            List<UserProfile> _getChild = new List<UserProfile>();
            populateChildBinary(userId, _getChild);
            return _getChild.Count();
        }
        public string _delUser(int _userId)
        {
            string _result = null;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var _idDel = db.UserProfiles.Where(x => x.UserId == _userId).FirstOrDefault();
                if (_idDel.Parent_ID == 0 || _idDel.ParentB_ID == 0 || _idDel.UserName == "root")
                    return _result = "Không thể xóa {root}";
                // lay danh sach Binary Child của user Del
                var _lsChildBinary = db.UserProfiles.Where(x => x.ParentB_ID == _idDel.UserId).ToList();
                if (_lsChildBinary.Count > 0)
                    return _result = "Thành viên có mã con nhị phân";
                // lay cha Binary
                var parentB = db.UserProfiles.Where(x => x.UserId == _idDel.ParentB_ID).FirstOrDefault();
                if (parentB != null)
                {
                    if (parentB.Left == _idDel.UserId)
                        parentB.Left = null;
                    if (parentB.Right == _idDel.UserId)
                        parentB.Right = null;
                }

                //lay danh sach Parent Child của user Del
                var _lsChildParent = db.UserProfiles.Where(x => x.Parent_ID == _idDel.UserId).ToList();
                if (_lsChildParent.Count > 0)
                {
                    _lsChildParent.ForEach(x => x.Parent_ID = (int)_idDel.Parent_ID);
                }
                db.UserProfiles.Remove(_idDel);
                db.SaveChanges();
                object[] parameters = { _idDel.UserId };
                var plugins = db.CommissionConfigs.Where(t => (t.Status == true));
                foreach (var plugin in plugins.ToList())
                {

                    string plugin_name = plugin.CommissionName + ".ExecuteCommission";
                    try
                    {
                        var instance = System.Activator.CreateInstance(Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service"));
                        var class_name = Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service");
                        var method = class_name.GetMethod("afterDeletedUser");
                        method.Invoke(instance, parameters);

                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
                return _result;
            }
        }
        // load data user 
        public Userloadata[] getListUserWithCondition(string searchType, string searchtext, string cbType)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var sql = from U in db.UserProfiles
                          join G in db.Groups
                          on U.GruopID equals G.GroupID
                          join p in db.UserProfiles on U.Parent_ID equals p.UserId into j1
                          join b in db.UserProfiles on U.ParentB_ID equals b.UserId into j2
                          from p in j1.DefaultIfEmpty()
                          from b in j2.DefaultIfEmpty()
                          select new Userloadata
                          {
                              STT = U.UserId,
                              UserName = U.UserName,
                              HoTen = U.HOTEN,
                              NgaySinh = U.NGAYSINH,
                              GIOITINH = U.GIOITINH,
                              DiaChi = U.DIACHI,
                              SCMND = U.SOCMND,
                              Email = U.EMAIL,
                              SoDT = U.SDTNHARIENG,
                              Level = U.Level,
                              PackageName = U.Package.PackageName,
                              Status = U.Status,
                              Parent_ID = p != null ? p.UserName : "",
                              ParentB_ID = b != null ? b.UserName : "",
                              NHOM = G.GroupName,
                              Pass = U.p
                          };
                if (searchType == "Username")
                {
                    sql = sql.Where(w => w.UserName.Contains(searchtext));

                }
                if (searchType == "Họ Tên")
                {
                    sql = sql.Where(w => w.HoTen.Contains(searchtext));
                }
                if (cbType != "Chọn Nhóm")
                {
                    sql = sql.Where(w => w.NHOM == cbType);

                }
                return sql.ToArray();
            }



        }
        // list Config
        public Config[] getlistConfig(string type = null)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                if (type == "")
                    return db.Configs.ToArray();
                return db.Configs.Where(w => w.Module_Id == type).ToArray();
            }
        }
        public int UpdateConFig(Config c)
        {
            int _rt = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var Config1 = db.Configs.Where(w => w.ID == c.ID).SingleOrDefault();
                Config1.Module_Id = c.Module_Id;
                Config1.Module_Name = c.Module_Name;
                Config1.Option_1 = c.Option_1;
                Config1.Option_2 = c.Option_2;
                Config1.Option_3 = c.Option_3;
                Config1.Option_4 = c.Option_4;
                Config1.Option_5 = c.Option_5;
                Config1.Desciption = c.Desciption;
                db.SaveChanges();
                _rt = 1;
            }
            return _rt;
        }
        //List Permmission
        public Permission[] getlistPermmission(int? id = null)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Permissions.ToArray();
            }
        }
        public Permission FindPermissionByGroupid(int grId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Permissions.Where(w => w.GroupId == grId).FirstOrDefault();
            }
        }
        // add permission
        public int AddPermmission(Permission per)
        {
            int _Return = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Permissions.Add(per);
                db.SaveChanges();
                _Return = 1;
            }

            return _Return;
        }
        // update permmission
        public int UpdatePermmission(Permission per)
        {
            int _Return = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var d = db.Permissions.Where(w => w.Permission_ID == per.Permission_ID).FirstOrDefault();
                d.Permission_1 = per.Permission_1;
                d.Permission_2 = per.Permission_2;
                d.Permission_3 = per.Permission_3;
                d.Permission_4 = per.Permission_4;
                d.Permission_5 = per.Permission_5;
                d.Permission_6 = per.Permission_6;
                d.Permission_7 = per.Permission_7;
                d.Permission_8 = per.Permission_8;
                d.Permission_9 = per.Permission_9;
                d.Permission_10 = per.Permission_10;
                db.SaveChanges();
                _Return = 1;
            }
            return _Return;
        }
        // group
        public Group[] getListGroup()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Groups.ToArray();
            }
        }
        public int Addgroup(Group c)
        {
            int _Return = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Groups.Add(c);
                db.SaveChanges();
                _Return = 1;
            }
            return _Return;
        }
        public int RemoveGroup(int id)
        {
            int _Return = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var removegroup = db.Groups.Where(w => w.GroupID == id).FirstOrDefault();
                db.Groups.Remove(removegroup);
                db.SaveChanges();
                _Return = 1;
            }
            return _Return;
        }
        public int UpdateGroup(Group c)
        {
            int _Return = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var d = db.Groups.Where(w => w.GroupID == c.GroupID).FirstOrDefault();
                d.GroupID = c.GroupID;
                d.GroupName = c.GroupName;
                d.Default = c.Default;
                db.SaveChanges();
                _Return = 1;
            }
            return _Return;
        }
        public Config getConfigTree()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                Config _cf = db.Configs.Where(x => x.Module_Id == "TreeSystem").ToList().FirstOrDefault();
                return _cf;
            }
        }
        public Config findConfigbyDynamic()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Configs.Where(x => x.Module_Id == "Dynamic").FirstOrDefault();
            }
        }
        public int Update(UserProfile OUserEdit)
        {
            int _rt = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var UserEdit = db.UserProfiles.Where(w => w.UserId == OUserEdit.UserId).SingleOrDefault();
                if (UserEdit == null) return 0;
                this.mapUserProfile(UserEdit, OUserEdit);
                db.SaveChanges();
                _rt = 1;
            }
            return _rt;
        }
        public OrderViewGroup[] level(int userId, DateTime? _keyword)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                List<OrderViewGroup> _model = new List<OrderViewGroup>();
                List<Order> _orderOfMonth = db.Orders.Where(x => x.Date.Value.Month == _keyword.Value.Date.Month && x.Date.Value.Year == _keyword.Value.Year).ToList();
                List<UserProfile> _allChild = new List<UserProfile>();
                populateChild(userId, _allChild);
                //levvel 1
                var floor1 = new List<UserProfile>();
                _allChild.ForEach(x =>
                {
                    if (x.Parent_ID == userId)
                    {
                        floor1.Add(x);
                    }
                });
                double _fee1 = Convert.ToDouble(_orderOfMonth.Join(floor1, c => c.UserId, p => p.UserId, (c, p) => new
                {
                    c.ID,
                    c.Pv,
                    c.Date
                }).Sum(s => s.Pv));
                _model.Add(new OrderViewGroup
                {
                    Amount = _fee1,
                    Date = _keyword,
                    Floor = 1,
                    Number = floor1.Count()
                });
                // het 1
                // qua 2
                var floor2 = new List<UserProfile>();
                _allChild.ForEach(x =>
                {
                    floor1.ForEach(s =>
                    {
                        if (x.Parent_ID == s.UserId)
                        {
                            floor2.Add(x);
                        }
                    });
                });
                double _fee2 = Convert.ToDouble(_orderOfMonth.Join(floor2, c => c.UserId, p => p.UserId, (c, p) => new
                {
                    c.ID,
                    c.Pv,
                    c.Date
                }).Sum(s => s.Pv));
                _model.Add(new OrderViewGroup
                {
                    Amount = _fee2,
                    Date = _keyword,
                    Floor = 2,
                    Number = floor2.Count()
                });
                // het 2
                // qua 3
                var floor3 = new List<UserProfile>();
                _allChild.ForEach(x =>
                {
                    floor2.ForEach(t =>
                    {
                        if (x.Parent_ID == t.UserId)
                        {
                            floor3.Add(x);
                        }
                    });

                });
                double _fee3 = Convert.ToDouble(_orderOfMonth.Join(floor3, c => c.UserId, p => p.UserId, (c, p) => new
                {
                    c.ID,
                    c.Pv,
                    c.Date
                }).Sum(s => s.Pv));
                _model.Add(new OrderViewGroup
                {
                    Amount = _fee3,
                    Date = _keyword,
                    Floor = 3,
                    Number = floor3.Count()
                });
                //het 3
                // qua 4
                var floor4 = new List<UserProfile>();
                _allChild.ForEach(x =>
                {
                    floor3.ForEach(r =>
                    {
                        if (x.Parent_ID == r.UserId)
                        {
                            floor4.Add(x);
                        }
                    });

                });
                double _fee4 = Convert.ToDouble(_orderOfMonth.Join(floor4, c => c.UserId, p => p.UserId, (c, p) => new
                {
                    c.ID,
                    c.Pv,
                    c.Date
                }).Sum(s => s.Pv));
                _model.Add(new OrderViewGroup
                {
                    Amount = _fee4,
                    Date = _keyword,
                    Floor = 4,
                    Number = floor4.Count()
                });
                // level 5
                var floor5 = new List<UserProfile>();
                _allChild.ForEach(x =>
                {
                    floor4.ForEach(o =>
                    {
                        if (x.Parent_ID == o.UserId)
                        {
                            floor5.Add(x);
                        }
                    });
                });
                double _fee5 = Convert.ToDouble(_orderOfMonth.Join(floor5, c => c.UserId, p => p.UserId, (c, p) => new
                {
                    c.ID,
                    c.Pv,
                    c.Date
                }).Sum(s => s.Pv));
                _model.Add(new OrderViewGroup
                {
                    Amount = _fee5,
                    Date = _keyword,
                    Floor = 5,
                    Number = floor5.Count()
                });
                //
                // level 6
                var floor6 = new List<UserProfile>();
                _allChild.ForEach(x =>
                {
                    floor5.ForEach(o =>
                    {
                        if (x.Parent_ID == o.UserId)
                        {
                            floor6.Add(x);
                        }
                    });

                });
                double _fee6 = Convert.ToDouble(_orderOfMonth.Join(floor6, c => c.UserId, p => p.UserId, (c, p) => new
                {
                    c.ID,
                    c.Pv,
                    c.Date
                }).Sum(s => s.Pv));
                _model.Add(new OrderViewGroup
                {
                    Amount = _fee6,
                    Date = _keyword,
                    Floor = 6,
                    Number = floor6.Count()
                });
                // level 7
                var floor7 = new List<UserProfile>();
                _allChild.ForEach(x =>
                {
                    floor6.ForEach(q =>
                    {
                        if (x.Parent_ID == q.UserId)
                        {
                            floor7.Add(x);
                        }
                    });

                });
                double _fee7 = Convert.ToDouble(_orderOfMonth.Join(floor7, c => c.UserId, p => p.UserId, (c, p) => new
                {
                    c.ID,
                    c.Pv,
                    c.Date
                }).Sum(s => s.Pv));
                _model.Add(new OrderViewGroup
                {
                    Amount = _fee7,
                    Date = _keyword,
                    Floor = 7,
                    Number = floor7.Count()
                });
                //
                return _model.ToArray();
            }

        }
        public void populateOrderGroupChild(int parentId, List<UserProfile> childrens)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var lsChild = db.UserProfiles.Where(x => x.Parent_ID == parentId).ToList();
                childrens.AddRange(lsChild);
                foreach (var item in lsChild)
                {
                    populateChild(item.UserId, childrens);
                }
            }
        }
        public int checkNangDong(int UserId, int month, int year)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                int _rt = 0;
                double _SumProfitforUser = Convert.ToDouble(db.Profits.Where(x => x.UserId == UserId && x.CreateDate.Value.Month == month && x.CreateDate.Value.Year == year).Sum(x => x.Amount));
                double _SumOderforUser = Convert.ToDouble(db.Orders.Where(w => w.UserId == UserId && w.Date.Value.Month == month && w.Date.Value.Year == year).Sum(x => x.Amount));
                if (_SumProfitforUser == 0 || _SumOderforUser == 0) return 0;
                else
                {   // return 0 la khong nang dong
                    // return 1 la nang dong
                    // thu nhap nho hon 2.5tr ko nang dong
                    if (_SumProfitforUser < 2500000) return 0;
                    // doanh so tu 2.5 -> 5tr
                    if (_SumProfitforUser >= 2500000 && _SumProfitforUser <= 5000000)
                    {
                        if (_SumOderforUser >= 400000)
                            _rt = 1;
                    }
                    // muc thu nhap tu 5tr -> 10tr
                    if (_SumProfitforUser > 5000000 && _SumProfitforUser <= 10000000)
                    {
                        if (_SumOderforUser >= 800000)
                            _rt = 1;
                    }
                    // kiem tra thu nhap tu 10 tr den 20tr
                    if (_SumProfitforUser > 10000000 && _SumProfitforUser <= 20000000)
                    {
                        if (_SumOderforUser >= 1500000)
                            _rt = 1;
                    }
                    // kiem tra dieu kien voi moc tu 20tr -> 50tr
                    if (_SumProfitforUser > 20000000 && _SumProfitforUser <= 50000000)
                    {
                        if (_SumOderforUser >= 3000000)
                            _rt = 1;
                    }
                    // kiem tra dieu kien voi moc tren 50tr
                    if (_SumProfitforUser > 50000000)
                    {
                        if (_SumOderforUser >= 6000000)
                            _rt = 1;
                    }
                }

                return _rt;
            }
        }
        public UserProfile chooseuser(int userId, string pass)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(w => w.UserId == userId && w.Password == pass).FirstOrDefault();
            }
        }
        public string[] getListUserSystemTree()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(x => x.Parent_ID != null).Select(o => o.UserName).ToArray();
            }
        }
        public string[] getListUserBinaryTree()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(x => x.ParentB_ID != null).Select(o => o.UserName).ToArray();
            }
        }
        public CommissionConfig[] ListCommission()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.CommissionConfigs.Where(w => w.Status == true).ToArray();
            }
        }
        public double? SumAmount(string CommissionName)
        {
            double? amount = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                amount = db.Profits.Where(w => w.ProfitType == CommissionName).Sum(s => s.Amount);
            }
            return amount;
        }
        public UserConfig ChooseConfigUser()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserConfigs.FirstOrDefault();
            }
        }
        public void UpdateUserConfig(UserConfig c)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var DTConfig = db.UserConfigs.Where(w => w.Id == c.Id).FirstOrDefault();
                DTConfig.AGUsername = c.AGUsername;
                DTConfig.Suffix = c.Suffix;
                db.SaveChanges();
            }
        }
        //Tuong
        // Chu KY
        public ChuKyConfig[] GetListChuKy()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.ChuKyConfigs.ToArray();
            }
        }
        public void AddChuKyConfig(ChuKyConfig c)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                db.ChuKyConfigs.Add(c);
                db.SaveChanges();
            }
        }
        public void UpdateChykyconfig(ChuKyConfig UD)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var Update = db.ChuKyConfigs.Where(w => w.ChuKyID == UD.ChuKyID).FirstOrDefault();
                Update.From = UD.From;
                Update.To = UD.To;
                Update.TenChuKy = UD.TenChuKy;
                db.SaveChanges();

            }
        }
        public ChuKyConfig ChooseChuKyConfig(int id)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.ChuKyConfigs.Where(w => w.ChuKyID == id).FirstOrDefault();
            }
        }
        public FillCombobox[] GetlistParentforcombobox()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(w => w.Parent_ID != null).Select(s => new FillCombobox { username = s.UserName, Userid = s.UserId }).ToArray();
            }
        }
        public FillCombobox[] GetlistBinaryidforcombobox()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(w => w.ParentB_ID != null).Select(s => new FillCombobox { username = s.UserName, Userid = s.UserId }).ToArray();
            }
        }
        public UserProfile[] getTreeParent(string userName)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var currentUser = db.UserProfiles.Where(x => x.UserName == userName).FirstOrDefault();
                List<UserProfile> _result = new List<UserProfile>();
                _result.Add(currentUser);
                populateChild(currentUser.UserId, _result);
                return _result.ToArray();
            }
        }
        public UserProfile[] getTreeBinary(string userName)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var currentUser = db.UserProfiles.Where(x => x.UserName == userName).FirstOrDefault();
                List<UserProfile> _result = new List<UserProfile>();
                _result.Add(currentUser);
                populateChildBinary(currentUser.UserId, _result);
                return _result.ToArray();
            }

        }
        public void RefershAll()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                foreach (var entity in db.ChangeTracker.Entries())
                {
                    entity.Reload();
                }
            }
        }
        public UserProfile findParent(int userid)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(x => x.UserId == userid).FirstOrDefault();
            }
        }
        public UserProfile[] getFloorChildByParentB_ID(int _parentBId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var _parentB = db.UserProfiles.Where(x => x.UserId == _parentBId).SingleOrDefault();
                IEnumerable<UserProfile> tt = Extension.BreadthFirstTopDownTraversal(_parentB, delegate (UserProfile u)
                {
                    var a = new List<UserProfile>();
                    var l = db.UserProfiles.Where(x => x.UserId == u.Left).SingleOrDefault();
                    var r = db.UserProfiles.Where(x => x.UserId == u.Right).SingleOrDefault();
                    if (l != null)
                        a.Add(l);
                    if (r != null)
                        a.Add(r);
                    return a;
                });
                return tt.Take(11).ToArray();
            }
        }
        public UserProfile[] getFloorChildByNary(int _parentBId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                List<UserProfile> _return = new List<UserProfile>();
                populateChildBinary(_parentBId, _return);
                _return.ToArray();
                return _return.ToArray();
            }
        }
        public Config findConfigById(string Id)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var _config = db.Configs.Where(x => x.Module_Id.Equals(Id)).FirstOrDefault();
                return _config;
            }

        }
        public Tuple<int, Userloadata[]> getListUserWithConditionPaging(string searchType, string searchtext, string cbType, int fromRange = 0, int toRange = 100)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var sql = from U in db.UserProfiles
                          join G in db.Groups
                          on U.GruopID equals G.GroupID
                          join p in db.UserProfiles on U.Parent_ID equals p.UserId into j1
                          join b in db.UserProfiles on U.ParentB_ID equals b.UserId into j2
                          from p in j1.DefaultIfEmpty()
                          from b in j2.DefaultIfEmpty()
                          select new Userloadata
                          {
                              STT = U.UserId,
                              UserName = U.UserName,
                              HoTen = U.HOTEN,
                              NgaySinh = U.NGAYSINH,
                              GIOITINH = U.GIOITINH,
                              DiaChi = U.DIACHI,
                              SCMND = U.SOCMND,
                              Email = U.EMAIL,
                              SoDT = U.SDTNHARIENG,
                              Level = U.Level,
                              PackageName = U.Package.PackageName,
                              Status = U.Status,
                              Parent_ID = p != null ? p.UserName : "",
                              ParentB_ID = b != null ? b.UserName : "",
                              NHOM = G.GroupName,
                              Pass = U.p,
                              CreateDate = U.CreateDate == null ? null : U.CreateDate,
                              Rank = (from m in db.LevelUsers
                                      where m.UserId == U.UserId
                                      join n in db.Achievements on m.LevelCode equals n.LevelCode
                                      select n.Name).FirstOrDefault()
                          };
                if (searchType == "Username")
                {
                    sql = sql.Where(w => w.UserName.Contains(searchtext));
                }
                if (searchType == "Họ Tên")
                {
                    sql = sql.Where(w => w.HoTen.Contains(searchtext));
                }
                if (searchType == "Chứng minh nhân dân")
                {
                    sql = sql.Where(w => w.SCMND.Contains(searchtext));
                }
                if (cbType != "Chọn Nhóm")
                {
                    sql = sql.Where(w => w.NHOM == cbType);
                }
                //sql = sql.OrderBy(s => s.STT);
                int _totalItem = sql.Count();//thu lai đi a....// build Lib
                if(_totalItem > 0)
                  {   
                    if (fromRange == 1 || fromRange == 0)
                        return new Tuple<int, Userloadata[]>(_totalItem, sql.OrderByDescending(o => o.STT).Skip(0).Take(toRange).ToArray());
                    else
                        return new Tuple<int, Userloadata[]>(_totalItem, sql.OrderByDescending(o => o.STT).Skip(fromRange).Take(toRange).ToArray());
                  }else
                {
                    return new Tuple<int, Userloadata[]>(0,sql.ToArray());
                }
            }
        }
        public void RemoveChukyConfig(int id)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var ckchoose = db.ChuKyConfigs.Where(w => w.ChuKyID == id).SingleOrDefault();
                db.ChuKyConfigs.Remove(ckchoose);
                db.SaveChanges();
            }
        }
        public void coutChildren(int? node, ref int count, ref double? amount)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {

                var dkThoat = db.UserProfiles.Where(w => w.UserId == node).SingleOrDefault();
                if (dkThoat == null) return;
                var O_node = from u in db.UserProfiles.Where(w => w.UserId == node && w.Status == true) join o in db.Orders.Where(w => w.Amount > 0) on u.UserId equals o.UserId select o;
                if (O_node != null)
                {
                    if (O_node.Sum(s => s.Amount) > 0)
                    {
                        amount = amount + O_node.Sum(s => s.Amount);
                        count++;
                    }
                    coutChildren(dkThoat.Left, ref count, ref amount);
                    coutChildren(dkThoat.Right, ref count, ref amount);
                }
            }
        }
        /**
         * 
         * @
         * */
        public int get5UserFirst()
        {
            int result;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                result = db.UserProfiles.OrderBy(o => o.UserId)
                    .Take(5)
                    .Select(s => s.UserId).OrderBy(x => Guid.NewGuid()).FirstOrDefault();
            }
            return result;
        }
        public bool checkMailInSystem(string mail)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                int result = db.UserProfiles.Where(x => x.EMAIL == mail).Count();
                return result > 0 ? true : false;
            }
        }
        public bool checkPhoneNumberInSystem(string PhoneNumber)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                int result = db.UserProfiles.Where(x => x.SDTNHARIENG.Contains(PhoneNumber)).ToList().Count;
                return result >= 6 ? true : false;
            }
        }
        public bool checkSoCMNDInSystem(string SoCMND)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                int result = db.UserProfiles.Where(x => x.SOCMND.Contains(SoCMND)).ToList().Count;
                return result >= 3 ? true : false;
            }
        }
        public bool checkUsernameInSystem(string Username)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                int result = db.UserProfiles.Where(x => x.UserName == Username).Count();
                return result > 0 ? true : false;
            }
        }
        public bool checkMailInSystemOtherUserID(string mail, int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                int result = db.UserProfiles.Where(x => x.EMAIL == mail && x.UserId != UserId).Count();
                return result > 0 ? true : false;
            }
        }
        public void InsertPinCode(Authorized_Code item)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                db.Authorized_Code.Add(item);
                db.SaveChanges();
            }
        }
        public bool CheckTimeLifePinCodeByEmail(string Email)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var authorized = db.Authorized_Code.Where(w => w.Email == Email).ToList();
                if (authorized != null)
                {
                    foreach (var author in authorized)
                    {
                        if (author.Createdate.Value.AddSeconds(author.During.Value) > DateTime.Now)
                        {
                            return true;
                        }
                        else
                        {
                            //remove pincode die
                            db.Authorized_Code.Remove(author);
                            db.SaveChanges();
                        }
                    }
                }
                return false;
            }
        }
        public bool checkPinCode(string pincode)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var result = db.Authorized_Code.Where(w => w.Code == pincode).FirstOrDefault();
                if (result != null)
                {
                    //check thoi gian song
                    //result.Createdate.Value.AddSeconds((double)result.During);
                    DateTime codeCreateDate = result.Createdate.Value;
                    codeCreateDate = codeCreateDate.AddSeconds((double)result.During.Value);
                    if (codeCreateDate > DateTime.Now)
                    {
                        return true;
                    }
                    else
                    {
                        db.Authorized_Code.Remove(result);
                        db.SaveChanges();
                        return false;
                    }
                }
                return false;
            }
        }
        public bool removePinCode(string pincode)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var result = db.Authorized_Code.Where(w => w.Code == pincode).FirstOrDefault();
                if (result != null)
                {
                    db.Authorized_Code.Remove(result);
                    db.SaveChanges();
                    return true;
                }
                return false;
            }
        }
        /**
         * @summary Change Password with exist pincode and time > time now
         * 
         * 
         * */
        public UserProfile changePasswordByPincode(string pincode, string password)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //check check thoi gian ton tai pincode
                var CodeItem = db.Authorized_Code.Where(w => w.Code == pincode).FirstOrDefault();
                var userchange = db.UserProfiles.Where(w => w.EMAIL == CodeItem.Email).FirstOrDefault();
                userchange.Password = this.MD5Hash(password);
                if (this.changPassword(userchange) > 0)
                {
                    db.Authorized_Code.Remove(CodeItem);
                    db.SaveChanges();
                    return userchange;
                }
                return null;
            }
        }
        public UserProfile changeEmailByUserId(string Email, int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //check check thoi gian ton tai pincode
                var user1 = db.UserProfiles.Where(w => w.UserId == UserId).FirstOrDefault();
                user1.EMAIL = Email;
                db.SaveChanges();
                return null;
            }
        }
        public string getEmailByPinCode(string pincode)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //check check thoi gian ton tai pincode               
                var CodeItem = db.Authorized_Code.Where(w => w.Code == pincode)
                    .Select(s => s.Email)
                    .FirstOrDefault();
                return CodeItem;
            }
        }
        public UserProfile getUserByEmail(string Email)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //check check thoi gian ton tai pincode               
                var userchange = db.UserProfiles.Where(w => w.EMAIL == Email).FirstOrDefault();
                return userchange;
            }
        }
        public string MD5Hash(string text)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));
            byte[] result = md5.Hash;
            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                strBuilder.Append(result[i].ToString("x2"));
            }
            return strBuilder.ToString();
        }
        public bool AfterUpgradeUser(int user_id, int tolevel, double amount, int? pv, int? OrderID, DateTime? Date)
        {
            object[] parameters = { user_id, amount, pv, OrderID, Date };
            string connection = DuAnDaCapEntities.getDomain();
            using (var staticdb = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var upgradedUser = staticdb.UserProfiles.Where(w => w.UserId == user_id).SingleOrDefault();
                if (upgradedUser == null)
                    return false;
                upgradedUser.Level = tolevel;
                upgradedUser.LevelUpdate = Date;
                staticdb.SaveChanges();

                var plugins = staticdb.CommissionConfigs.Where(t => (t.Status == true));
                foreach (var plugin in plugins.ToList())
                {
                    string plugin_name = plugin.CommissionName + ".ExecuteCommission";
                    try
                    {
                        var instance = System.Activator.CreateInstance(Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service"));
                        var class_name = Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service");
                        var method = class_name.GetMethod("AterUserUpgrade");
                        method.Invoke(instance, parameters);

                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
                return true;
            }
        }
        public List<UserLevel> getUserLevels()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var userLevels = db.UserLevels.ToList();
                //var result = db.Wallets.ToArray();
                return userLevels;
            }
        }
        public UserLevel getUserLevelById(int LevelId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var userLevels = db.UserLevels.Where(w => w.Id == LevelId).FirstOrDefault();
                //var result = db.Wallets.ToArray();
                return userLevels;
            }
        }
        public bool PayWallet(int UserId, int WalletId, double Fees)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    db.Configuration.ProxyCreationEnabled = false;
                    var transaction = new LKVService.Transaction();
                    var WalletDetail = db.Wallet_Detail.Where(w => w.UserID == UserId && w.WalletID == WalletId).FirstOrDefault();
                    WalletDetail.Balance = WalletDetail.Balance - Fees;
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    return false;
                }
                return true;
            }
        }
        public bool UpdatePerfectMoney(int UserId, string Unit, string Account, string Payer, string Name)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    db.Configuration.ProxyCreationEnabled = false;
                    var PerfectAccount = db.PerfectMoneyUsers.Where(w => w.UserId == UserId).FirstOrDefault();
                    //have account
                    if (PerfectAccount != null)
                    {
                        PerfectAccount.Account = Account;
                        PerfectAccount.PaymentUnit = Unit;
                        PerfectAccount.Payer = Payer;
                        PerfectAccount.Name = Name;
                        db.SaveChanges();
                    }
                    else
                    {
                        var AccountNew = new PerfectMoneyUser();
                        AccountNew.UserId = UserId;
                        AccountNew.Account = Account;
                        AccountNew.PaymentUnit = Unit;
                        AccountNew.Payer = Payer;
                        AccountNew.Name = Name;
                        db.PerfectMoneyUsers.Add(AccountNew);
                        db.SaveChanges();
                    }
                }
                catch (Exception)
                {
                    return false;
                }
                return true;
            }
        }
        // Function by HoangNguyen
        public FeeConfig getFeeConfig()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //check check thoi gian ton tai pincode               
                return db.FeeConfigs.FirstOrDefault();
            }
        }
        public bool RemoveUserLevel(int id = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //check check thoi gian ton tai pincode               
                var choose = db.UserLevels.Where(w => w.Id == id).SingleOrDefault();
                if (choose != null)
                {
                    db.UserLevels.Remove(choose);
                    db.SaveChanges();
                    return true;
                }
                else
                    return false;
            }
        }
        public bool AddUserLevel(UserLevel c)
        {
            bool result = false;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                db.UserLevels.Add(c);
                db.SaveChanges();
                result = true;
                return result;
            }
        }
        public bool UpdateUserLevel(UserLevel ud)
        {
            bool result = false;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var chooseUSLV = db.UserLevels.Where(w => w.Id == ud.Id).SingleOrDefault();
                chooseUSLV.Name = ud.Name;
                chooseUSLV.Amount = ud.Amount;
                chooseUSLV.Maximum = ud.Maximum;
                chooseUSLV.Minimum = ud.Minimum;
                db.SaveChanges();
                result = true;
                return result;
            }
        }
        public List<FeeConfig> ListFeeConfig()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.FeeConfigs.ToList();
            }
        }
        public bool UpdateFeeConfig(FeeConfig ud)
        {
            bool result = false;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var chooseUSLV = db.FeeConfigs.Where(w => w.Id == ud.Id).SingleOrDefault();
                chooseUSLV.Addfund = ud.Addfund;
                chooseUSLV.Cashout = ud.Cashout;
                chooseUSLV.BuyStock = ud.BuyStock;
                chooseUSLV.SellStock = ud.SellStock;
                chooseUSLV.PremiumEdit = ud.PremiumEdit;
                db.SaveChanges();
                result = true;
                return result;
            }
        }
        public List<CauHinhQuy> LoadListCaskBankConfig()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var loaddata = from u in db.UserProfiles
                               join c in db.CashBankConfigs
                               on u.UserId equals c.UserId
                               select new CauHinhQuy
                               {
                                   UserId = u.UserId,
                                   UserName = u.UserName,
                                   HoTen = u.HOTEN,
                                   Type = c.Type,
                                   Percent = c.Percent
                               };
                return loaddata.ToList();
            }
        }
        public bool RemoveCaskBankConfig(int userid)
        {
            bool result = false;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {

                var choose = db.CashBankConfigs.Where(w => w.UserId == userid).SingleOrDefault();
                if (choose != null)
                {
                    db.CashBankConfigs.Remove(choose);
                    db.SaveChanges();
                    result = true;
                }
                return result;
            }
        }
        public bool AddCaskBankConfig(CashBankConfig c)
        {
            bool result = false;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.CashBankConfigs.Add(c);
                db.SaveChanges();
                result = true;
            }
            return result;

        }
        public bool UpdateCaskBankConfig(CashBankConfig ud)
        {
            bool result = false;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var chooseCb = db.CashBankConfigs.Where(w => w.UserId == ud.UserId).SingleOrDefault();
                chooseCb.Type = ud.Type;
                chooseCb.Percent = ud.Percent;
                db.SaveChanges();
                result = true;
            }
            return result;

        }
        public CashBankConfig GetCaskBankConfig(int userid)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.CashBankConfigs.Where(w => w.UserId == userid).SingleOrDefault();

            }
        }
        public List<Country> getCountryList()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.Countries.ToList();
            }
        }
        public UserProfile findUserByBankType(string banktype)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var cash_config = db.CashBankConfigs.Where(w => w.Type == banktype).FirstOrDefault();
                var userCash = db.UserProfiles.Where(w => w.UserId == cash_config.UserId).FirstOrDefault();
                return userCash;
            }

        }
        public UserProfile[] findUsersByBankType(string banktype)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var result = from c in db.CashBankConfigs.Where(w => w.Type == banktype)
                             join u in db.UserProfiles on c.UserId equals u.UserId
                             select u;
                return result.ToArray();
            }

        }
        public WalletHistory[] FindWalletHistoryByUserToDay(int userid, int? waletid, DateTime date)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.WalletHistories.Where(w => w.WalletId == waletid && w.UserId == userid && w.CreateDate.Day == date.Day && w.CreateDate.Month == date.Month && w.CreateDate.Year == date.Year).ToArray();
            }
        }
        public Withdrawal[] FindWithdrawalByUser(int userid, int waletid, DateTime date, int status)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Withdrawals.Where(w => w.UserId == userid && w.WalletId == waletid && w.Create_Date.Value.Day == date.Day && w.Create_Date.Value.Month == date.Month && w.Create_Date.Value.Year == date.Year && w.Status == status).ToArray();
            }
        }
        public WalletHistory[] getListWalletHistory()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.WalletHistories.ToArray();
            }
        }
        public Withdrawal[] getListWithdrawals()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Withdrawals.ToArray();
            }
        }
        public double SumTotalforUserInWalletHistory(int userid, int? waletid)
        {
            double a = 0;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var list = db.WalletHistories.Where(w => w.UserId == userid && w.WalletId == waletid).ToList();
                if (list.Count() > 0)
                    a = Convert.ToDouble(list.Sum(s => s.Amount));
            }
            return a;
        }
        public UserProfile[] getListUserByGroup(int groupId = 0, string groupName = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                if (groupId > 0 && String.IsNullOrEmpty(groupName))
                    return db.UserProfiles.Where(w => w.Status != null && w.Status.Value == true && w.GruopID == groupId).ToArray();
                if (groupId == 0 && !String.IsNullOrEmpty(groupName))
                    return db.UserProfiles.Join(db.Groups.Where(w => w.GroupName.Equals(groupName)), c => c.GruopID, p => p.GroupID, (c, p) => new { user = c, group = p }).Select(s => s.user).ToArray();
                else
                    return db.UserProfiles.Join(db.Groups.Where(w => w.GroupID == groupId && w.GroupName.Equals(groupName)), c => c.GruopID, p => p.GroupID, (c, p) => new { user = c, group = p }).Select(s => s.user).ToArray();
            }
        }
        public UserProfile[] getListUserByGroupNotActive(int groupId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.UserProfiles.Where(w => w.GruopID == groupId).ToArray();
            }
        }
        public List<JsTreeAjaxModel> GetTreeRoot(int UserId)
        {
            var ListTree = new List<JsTreeAjaxModel>();
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var userRoot = db.UserProfiles.Where(w => w.UserId == UserId).FirstOrDefault();
                if (userRoot != null)
                {
                    bool isChildren = false;
                    var totalF1 = db.UserProfiles.Where(w => w.Parent_ID == userRoot.UserId).Count();
                    var childs = db.UserProfiles.Where(w => w.Parent_ID == userRoot.UserId).Count();
                    if (childs > 0)
                        isChildren = true;
                    double invest;
                    var orderUser = db.Orders.Where(w => w.UserId == userRoot.UserId);
                    if (orderUser.FirstOrDefault() != null)
                    {
                        invest = orderUser.Sum(s => s.Amount).Value;
                    }
                    else
                    {
                        invest = 0.0;
                    }

                    ListTree.Add(
                        new JsTreeAjaxModel()
                        {
                            id = userRoot.UserId != 0 ? userRoot.UserId.ToString() : null,
                            parent = "#",
                            text = userRoot.HOTEN != null ? userRoot.UserName + " " + "(" + userRoot.HOTEN + ")" : userRoot.UserName,
                            icon = userRoot.Status == true ? "fa fa-user text-active" : "fa fa-user text-unactive",
                            //state = new StateTree { opened = false, disabled = false, selected = false },
                            children = isChildren,
                            data = new NodeDataAccountInfo
                            {
                                downlineId = userRoot.UserId,
                                HoTen = userRoot.HOTEN,
                                UserName = userRoot.UserName,
                            }
                        }
                    );
                }
                return ListTree;
            }
        }
        public List<JsTreeAjaxModel> GetTreeChildrenByRoot(int UserId)
        {
            var ListTree = new List<JsTreeAjaxModel>();
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var userRoot = db.UserProfiles.Where(w => w.UserId == UserId).FirstOrDefault();
                var totalF1 = db.UserProfiles.Where(w => w.Parent_ID == userRoot.UserId).ToList();
                if (userRoot != null)
                {
                    var childs = db.UserProfiles.Where(w => w.Parent_ID == userRoot.UserId).ToList();
                    childs.ForEach(
                            x =>
                            {
                                ListTree.Add(
                                    new JsTreeAjaxModel()
                                    {
                                        id = x.UserId != 0 ? x.UserId.ToString() : null,
                                        parent = userRoot.UserId != 0 ? userRoot.UserId.ToString() : "#",
                                        text = x.HOTEN != null ? x.UserName + " " + "(" + x.HOTEN + ")" : x.UserName,
                                        icon = x.Status == true ? "fa fa-user text-active" : "fa fa-user text-unactive",
                                        //state = new StateTree { opened = true, disabled = false, selected = false },
                                        children = childs.Count > 0 ? true : false,
                                        data = new NodeDataAccountInfo
                                        {
                                            downlineId = x.UserId,
                                            HoTen = x.HOTEN,
                                            UserName = x.UserName
                                        }
                                    });
                            }
                        );
                }
                return ListTree;
            }
        }
        public int countChildBinaryByParentBId(int parentBId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.UserProfiles.Where(w => w.ParentB_ID == parentBId).Count();
            }
        }
        public double getInvestByUser(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                if (user == null)
                    return 0;
                return db.Orders.Where(w => w.UserId != null && w.UserId == userId).ToList().Count > 0 ? db.Orders.Where(w => w.UserId != null && w.UserId == userId).Sum(s => s.Amount != null ? s.Amount.Value : 0) : 0;

            }
        }
        public DropDownUser[] getListUserExceptLogin(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                var lsOfUser = getTreeParent(user.UserName).ToList();
                lsOfUser = lsOfUser.Where(w => w.UserId != user.UserId).ToList();
                var rt = lsOfUser.Select(s => new DropDownUser
                {
                    FullName = s.HOTEN,
                    Id = s.UserId,
                    UserName = s.UserName,
                    Status = s.Status == null || s.Status.Value == false ? false : true
                }).ToArray();
                return rt;
            }
        }
        public UserProfile[] getListUserRegisterIn5days()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.UserProfiles.Where(w => w.CreateDate != null && SqlFunctions.DateDiff("DAY", w.CreateDate.Value, DateTime.Now) < 6).ToArray();
            }
        }
        // Tường bổ sung - Dự Án <Anh Quế>
        /// <summary>
        /// cập nhật UserLevel khi add order thành công
        /// </summary>
        /// <param name="userId"></param>
        public void updateUserLevelAfterAddOrder(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    if (userId == 0)
                        return;
                    var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                    if (user == null)
                        return;
                    //trường hợp <user> có F1, kiểm tra xem số lượng và cấp độ đủ điều kiện thì lên cấp cho <user>
                    var lstF1User = db.UserProfiles.Where(w => w.Parent_ID == user.UserId && w.Status == true).ToList();
                    if (lstF1User.Count > 0)
                    {
                        // lấy level hiện tại của <user>
                        var cLevelUser = db.LevelUsers.Where(w => w.UserId == user.UserId).FirstOrDefault();
                        //lấy level tiếp theo
                        var nextLevelCodeUser = getNextLevelCode(cLevelUser.LevelCode);
                        //lấy điều kiện để đạt level này
                        var nextLevelUser = db.Achievements.Where(w => w.LevelCode.Equals(nextLevelCodeUser)).FirstOrDefault();
                        if (nextLevelUser.LevelChild.Equals("D"))
                        {
                            //đủ điều kiện thì lên cấp
                            if (lstF1User.Count >= nextLevelUser.Condition)
                            {
                                cLevelUser.LevelCode = nextLevelCodeUser;
                                db.SaveChanges();
                            }
                            else
                            {
                                //nếu level hiện tại không phải là <D> thì bắt đầu kiểm tra điều kiện F1 có đạt yêu cầu về level không (vd: S thì cần 5 F1 là A)
                                //lấy số lượng F1 đạt yêu cầu về Level cần
                                var lsF1UserTrue = db.LevelUsers.Where(w => w.LevelCode.Equals(nextLevelUser.LevelChild)).AsEnumerable().Join(lstF1User.AsEnumerable(), c => c.UserId, p => p.UserId, (c, p) => new { level = c, user = p }).Select(s => s.level).ToList();
                                //đạt yêu cầu thì <parent> lên cấp
                                if (lsF1UserTrue.Count >= nextLevelUser.Condition)
                                {
                                    cLevelUser.LevelCode = nextLevelCodeUser;
                                    db.SaveChanges();
                                }
                            }
                        }
                    }

                    var parent = db.UserProfiles.Where(w => w.UserId == user.Parent_ID && w.Status == true).FirstOrDefault();
                    while (parent != null)
                    {
                        //c: current
                        //lấy level hiện tại của <parent>
                        var clevel = db.LevelUsers.Where(w => w.UserId == parent.UserId).FirstOrDefault();
                        if (clevel == null)
                        {
                            parent = db.UserProfiles.Where(w => w.UserId == parent.Parent_ID).FirstOrDefault();
                            continue;
                        }

                        //kiểm ta xem có phải là level <S> cao nhất không, nếu đúng thì không cần kiểm tra lên level nữa
                        var uLevel = db.Achievements.Where(w => w.LevelCode.Equals(clevel.LevelCode)).FirstOrDefault();
                        if (uLevel.IsMax == true)
                        {
                            parent = db.UserProfiles.Where(w => w.UserId == parent.Parent_ID).FirstOrDefault();
                            continue;
                        }
                        //lấy level tiếp theo
                        var nextLevelCode = getNextLevelCode(clevel.LevelCode);
                        //lấy điều kiện để đạt level này
                        var nextLevel = db.Achievements.Where(w => w.LevelCode.Equals(nextLevelCode)).FirstOrDefault();
                        //lấy danh sách F1 của <parent>
                        var lstF1 = db.UserProfiles.Where(w => w.Parent_ID == parent.UserId && w.Status == true).ToList();
                        if (lstF1.Count == 0)
                        {
                            parent = db.UserProfiles.Where(w => w.UserId == parent.Parent_ID).FirstOrDefault();
                            continue;
                        }
                        //nếu hiện tại đang là level <D> là người mới và cấp tiếp theo <C> thì cần 5 F1
                        if (nextLevel.LevelChild.Equals("D"))
                        {
                            //đủ điều kiện thì lên cấp
                            if (lstF1.Count >= nextLevel.Condition)
                            {
                                clevel.LevelCode = nextLevelCode;
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            //kiểm tra xem ở level hiện tại <parent> có thỏa điều kiện chưa, chưa thì tìm xem <parent> nên ở level nào
                            if (lstF1.Count < uLevel.Condition)
                            {
                                //lấy danh sách level có số lượng F1 thỏa , xếp theo level từ nhỏ đến lớn
                                var fitLevel = db.Achievements.Where(w => w.Condition != null && w.Condition.Value != 0 && w.Condition.Value <= lstF1.Count).OrderBy(o => o.Ordinal).ToList();
                                var maxLevelFind = fitLevel.LastOrDefault().Ordinal;
                                if (fitLevel.Count == 0)
                                {
                                    parent = db.UserProfiles.Where(w => w.UserId == parent.Parent_ID).FirstOrDefault();
                                    continue;
                                }
                                if (fitLevel.Count == 1)
                                {
                                    var lsF1True = db.LevelUsers.Where(w => w.LevelCode.Equals(fitLevel[0].LevelCode)).AsEnumerable().Join(lstF1.AsEnumerable(), c => c.UserId, p => p.UserId, (c, p) => new { level = c, user = p }).Select(s => s.level).ToList();
                                    if (lsF1True.Count >= fitLevel[0].Condition)
                                    {
                                        clevel.LevelCode = fitLevel[0].LevelCode;
                                    }
                                }
                                else
                                {
                                    string tempLevelCode = String.Empty;
                                    foreach (var item in fitLevel)
                                    {
                                        var lsF1True = db.LevelUsers.Where(w => w.LevelCode.Equals(item.LevelChild)).AsEnumerable().Join(lstF1.AsEnumerable(), c => c.UserId, p => p.UserId, (c, p) => new { level = c, user = p }).Select(s => s.level).ToList();
                                        if (item.Ordinal != maxLevelFind)
                                        {
                                            if (lsF1True.Count >= item.Condition)
                                            {
                                                tempLevelCode = item.LevelCode;
                                            }
                                        }
                                        else
                                        {
                                            if (lsF1True.Count >= item.Condition)
                                            {
                                                clevel.LevelCode = item.LevelCode;
                                                break;
                                            }
                                            if (!String.IsNullOrEmpty(tempLevelCode))
                                            {
                                                clevel.LevelCode = tempLevelCode;
                                                break;
                                            }
                                        }
                                    }
                                }
                                db.SaveChanges();
                            }
                            else
                            {
                                //nếu level hiện tại không phải là <D> thì bắt đầu kiểm tra điều kiện F1 có đạt yêu cầu về level không (vd: S thì cần 5 F1 là A)
                                //lấy số lượng F1 đạt yêu cầu về Level cần
                                var lsF1True = db.LevelUsers.Where(w => w.LevelCode.Equals(nextLevel.LevelChild)).AsEnumerable().Join(lstF1.AsEnumerable(), c => c.UserId, p => p.UserId, (c, p) => new { level = c, user = p }).Select(s => s.level).ToList();
                                //đạt yêu cầu thì <parent> lên cấp
                                if (lsF1True.Count >= nextLevel.Condition)
                                {
                                    clevel.LevelCode = nextLevelCode;
                                    db.SaveChanges();
                                }
                            }

                        }

                        parent = db.UserProfiles.Where(w => w.UserId == parent.Parent_ID).FirstOrDefault();
                    }
                }
                catch (Exception em)
                {
                    return;
                }
            }
        }
        /// <summary>
        /// Tường: Cấp độ User theo thứ tự từ thấp đến cao D->C->B->A->S
        /// Hàm lấy cấp độ tiếp theo
        /// </summary>
        /// <param name="currentLevel"></param>
        /// <returns>Level Code</returns>
        public string getNextLevelCode(string currentLevel = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                string nextLevel = "";
                switch (currentLevel)
                {
                    case "D":
                        nextLevel = "C";
                        break;
                    case "C":
                        nextLevel = "B";
                        break;
                    case "B":
                        nextLevel = "A";
                        break;
                    case "A":
                        nextLevel = "S";
                        break;
                }

                return nextLevel;
            }
        }
        public Achievement findAchievementByUserId(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var achie = from us in db.UserProfiles.Where(u => u.UserId == userId)
                            join lev in db.LevelUsers on us.UserId equals lev.UserId
                            join ach in db.Achievements on lev.LevelCode equals ach.LevelCode
                            select ach;
                return achie.FirstOrDefault();
            }
        }
        public bool checkEmailByUserId(string email, int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var result = db.UserProfiles.Where(w => w.EMAIL == email && w.UserId == UserId).Count();
                return result > 0 ? true : false;
            }
        }
        public int countPhone(string phone = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                if (String.IsNullOrWhiteSpace(phone))
                    return 0;
                var result = db.UserProfiles.Where(w => w.SDTNHARIENG.Equals(phone)).Count();
                return result;
            }
        }
        public int countBank(string bank = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var result = db.UserProfiles.Where(w => w.SoTaiKhoan.Equals(bank)).Count();
                return result;
            }
        }
        //Thay đổi mật khẩu cấp 2
        public bool changePasswordLevel2(int userId = 0, string password2 = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try { 
                var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                user.SecondPassword = this.MD5Hash(password2);
                db.SaveChanges();
                return true;
                }catch(Exception em)
                {
                    return false;
                }
            }
        }
        //kiểm tra xem user có đang PH ko
        public bool checkUserInPH(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    var lsPH = db.PHs.Where(w => w.UserId != null && w.UserId == userId && (w.Status == 1)).ToList();
                    if (lsPH.Count > 0)
                        return true;
                    else
                        return false;
                }
                catch (Exception em)
                {
                    return true;
                }
            }
        }
        //lấy  Banks
        public BankList findBankById(int bankId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.BankLists.Where(w => w.Id == bankId).FirstOrDefault();
            }
        }
        //Hàm lấy Email support
        public EmailConfig findEmailById(int mailId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.EmailConfigs.FirstOrDefault(f => f.Id == mailId);
            }
        }
    }
    public class CommissionAmount
    {
        public string CommissionName { get; set; }
        public double? Amount { get; set; }
        public DateTime? Date { get; set; }
        public string CommissionDesc { get; set; }
    }
    public class Userloadata
    {
        public int? STT { get; set; }
        public string UserName { get; set; }
        public string HoTen { get; set; }
        public DateTime? NgaySinh { get; set; }
        public string NHOM { get; set; }
        public string GIOITINH { get; set; }
        public string DiaChi { get; set; }
        public string SCMND { get; set; }
        public string Email { get; set; }
        public string SoDT { get; set; }
        public int? Level { get; set; }
        public string PackageName { get; set; }
        public bool? Status { get; set; }
        public string Parent_ID { get; set; }
        public string ParentB_ID { get; set; }
        public string Pass { get; set; }
        public DateTime? CreateDate { get; set; }
        public string Rank { get; set; }
        
    }

    public class OrderMonth
    {
        public int? UserId { get; set; }
        public string UserName { get; set; }
        public string HOTEN { get; set; }
        public double? Amount { get; set; }
        public DateTime? Date { get; set; }
        public string ID_Order { get; set; }
    }
    public class OrderViewGroup
    {
        public int? Floor { get; set; }

        public int? Number { get; set; }

        public double? Amount { get; set; }

        public DateTime? Date { get; set; }

        public int? Stt { get; set; }
    }
    public class FillCombobox
    {
        public int Userid { get; set; }
        public string username { get; set;}
    }
    public class ProfitMonth
    {
        //  c.UserId, p.UserName, p.HOTEN, c.Amount, c.CreateDate, c.Decription 
        public int? UserId { get; set; }
        public string UserName { get; set; }
        public string HOTEN { get; set; }
        public double? Amount { get; set; }
        public DateTime? CreateDate { get; set; }
        public string Decription { get; set; }

    }
    public class CauHinhQuy
    {
        public int UserId { get; set; }
        public string Type { get; set; }
        public string UserName { get; set; }
        public string HoTen { get; set; }
        public double? Percent { get; set; }
    }
    public class JsTreeAjaxModel
    {
        public string id { get; set; }
        public string parent { get; set; }
        public string text { get; set; }
        public NodeDataAccountInfo data { get; set; }
        public string icon { get; set; }
        public StateTree state { get; set; }
        public bool children { get; set; }

    }
    public class StateTree
    {
        public bool opened { get; set; }
        public bool disabled { get; set; }
        public bool selected { get; set; }
    }
    public class NodeDataAccountInfo
    {
        public int downlineId { get; set; }
        public string UserName { get; set; }
        public string HoTen { get; set; }
    }
    public class DropDownUser
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string FullName { get; set; }
        public bool Status { get; set; }
    }
}
